package wang.juc3;

import lombok.SneakyThrows;
import org.junit.Test;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * Demo16
 *
 * @author HanQuinn
 * Date: 2022/7/16
 * Time: 14:07
 */
public class Demo0716_AtomicStampedReference {
    @SneakyThrows
    @Test
    public void run1() {
        String a = "\\D:\\myCode\\sineCode\\mcms\\ms-mcms\\target\\classes\\net\\mingsoft\\template\\1\\";

        String s = a.substring(1, 48) + "webapp";
        System.out.println(s);
    }


    @SneakyThrows
    @Test
    public void run() {
        AtomicStampedReference<Integer> stampedReference = new AtomicStampedReference<Integer>(10, 0);
        Thread t1 = new Thread(() -> {
            int stamp = stampedReference.getStamp();
            boolean result = stampedReference.compareAndSet(10, 11, stamp, ++stamp);
            System.out.println(Thread.currentThread().getName() + ":result = " + result);
            result = stampedReference.compareAndSet(11, 10, stamp, ++stamp);
            System.out.println(Thread.currentThread().getName() + ":result = " + result);
        }, "t1");
        Thread t2 = new Thread(() -> {
            boolean result = false;
            try {
                while (!result) {
                    int stamp = stampedReference.getStamp();
                    Thread.sleep(20);
                    result = stampedReference.compareAndSet(10, 11, stamp, ++stamp);
                    System.out.println(Thread.currentThread().getName() + ":result = " + result);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t2");

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("end");
    }


    class Simple {
        private String name;
        private int age;

        public Simple(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "Simple{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
}
